package liangtWorkSpace.threadDemo.thread.JUC;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liangt
 * @ClassName: CountDownLatchSimple
 * @title: CountDownLatchSimple
 * @projectName liangtWorkSpace.threadDemo.thread.JUC
 * @description: 计数器--执行指定计数器数量之后才会关闭线程
 * @date 2020/11/5 13:23
 */
public class CountDownLatchSimple {
    private static int index = 0;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        CountDownLatch cd = new CountDownLatch(10000);
        for (int i = 1; i <= 10000; i++) {
            final int num = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
//                    add(num);
                    try {
                        index = index + num;
                    }catch (Exception e){

                    }finally {
                        cd.countDown();
                    }
                }
            });
        }
        try {
            cd.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(index);
        executorService.shutdownNow();
    }
    private static void add(int num){
        synchronized (CountDownLatchSimple.class){
            index = index + num;
        }
    }
}
